package com.ytjj.qmyx.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.ytjj.common.constants.QueueConstants;
import com.ytjj.common.constants.RedisConstants;
import com.ytjj.common.enums.ProductStatusEnums;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.service.RedisService;
import com.ytjj.common.utils.HttpClientUtil;
import com.ytjj.qmyx.admin.client.BankerClient;
import com.ytjj.qmyx.admin.config.SupplyApiConfig;
import com.ytjj.common.constants.PlatformConstant;
import com.ytjj.qmyx.admin.dao.BankerProductDao;
import com.ytjj.qmyx.admin.dao.GoodsDao;
import com.ytjj.qmyx.admin.dao.ProductDao;
import com.ytjj.qmyx.admin.dao.ProductSpecDao;
import com.ytjj.qmyx.admin.dao.channel.SalesChannelsManagementDao;
import com.ytjj.qmyx.admin.eunm.ActivityEnums;
import com.ytjj.qmyx.admin.mapper.ProductAndCategoryMapper;
import com.ytjj.qmyx.admin.model.ProductAndCategory;
import com.ytjj.qmyx.admin.model.ProductAndCategoryExample;
import com.ytjj.qmyx.admin.model.SalesChannelsManagement;
import com.ytjj.qmyx.admin.model.request.UpdateSkuRequest;
import com.ytjj.qmyx.admin.model.request.channel.ChannelGoodsRequest;
import com.ytjj.qmyx.admin.model.request.goods.GetEvaluationFeedbackRequest;
import com.ytjj.qmyx.admin.model.request.goods.GetEvaluationInfoRequest;
import com.ytjj.qmyx.admin.model.request.goods.GoodsRequest;
import com.ytjj.qmyx.admin.model.response.BankerProduct.BankerProductDetailResponse;
import com.ytjj.qmyx.admin.model.response.goods.*;
import com.ytjj.qmyx.admin.service.GoodsService;
import com.ytjj.qmyx.admin.service.channelProductService.ChannelProductService;
import com.ytjj.qmyx.mall.mapper.ProductMapper;
import com.ytjj.qmyx.mall.model.BankerBrand;
import com.ytjj.qmyx.mall.model.Product;
import com.ytjj.qmyx.mall.model.ProductExample;
import com.ytjj.qmyx.mall.model.ProductSpec;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import static java.lang.Integer.parseInt;

/**
 * *
 **/
@Service
@Slf4j
public class GoodsServiceImpl implements GoodsService {

    @Resource
    private GoodsDao goodsDao;

    @Resource
    private ProductDao productDao;
    @Resource
    private ProductMapper productMapper;

    @Resource
    private BankerProductDao bankerProductDao;

    @Autowired
    private BankerClient bankerClient;

    @Resource
    private ProductAndCategoryMapper productAndCategoryMapper;

    @Resource
    private SupplyApiConfig supplyApiConfig;
    @Autowired
    private RedisService redisService;
    @Resource
    private ChannelProductService channelProductService;
    @Resource
    private ProductSpecDao productSpecDao;

    @Resource(name = "guchuangRabbitTemplate")
    private RabbitTemplate guchuangRabbitTemplate;

//    @Resource(name = "jumaiduoRabbitTemplate")
//    private RabbitTemplate jumaiduoRabbitTemplate;
//
//    @Resource(name = "yiquanRabbitTemplate")
//    private RabbitTemplate yiquanRabbitTemplate;
//
//    @Resource(name = "zxlpRabbitTemplate")
//    private RabbitTemplate zxlpRabbitTemplate;
//
//    @Resource(name = "ygyxRabbitTemplate")
//    private RabbitTemplate ygyxRabbitTemplate;
//
//    @Resource(name = "yxhdRabbitTemplate")
//    private RabbitTemplate yxhdRabbitTemplate;
//
//    @Resource(name = "jckjRabbitTemplate")
//    private RabbitTemplate jckjRabbitTemplate;


    @Resource
    private SalesChannelsManagementDao salesChannelsManagementDao;

    @Override
    public GoodsResponse getGoodsInfo(Integer goodsId) {
        GoodsResponse goodsResponse = goodsDao.getGoodsInfo(goodsId);
        List<ProductSkuKeyResponse> skuKey = goodsDao.findSku(goodsId);
        List<ProductImgResponse> bannerList = goodsDao.findImg(goodsId, "banner");
        List<ProductImgResponse> infoList = goodsDao.findImg(goodsId, "info");
        List<ProductSpecResponse> spec = goodsDao.findSpec(goodsId);
        goodsResponse.setSkuKey(skuKey);
        goodsResponse.setBannerList(bannerList);
        goodsResponse.setInfoList(infoList);
        goodsResponse.setSpec(spec);
        Integer bankerBrandId = queryBankerProduct(goodsResponse.getBankerProductId());
        goodsResponse.setBankerBrandId(bankerBrandId);
        return goodsResponse;
    }

    @Override
    public String selectContryListNew() {
        String resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/banker/new_country_list", null, supplyApiConfig.getHeadsMap());
        return resultJson;
    }

    @Override
    public String selectProductUnitNew() {
        String resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/banker/new_product_unit", null, supplyApiConfig.getHeadsMap());
        return resultJson;
    }


    @Override
    public String getGoodsInfoNew(Integer goodsId) {
        Map map = new HashMap();
        map.put("productId", String.valueOf(goodsId));
        String resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/banker/productDetail", map, supplyApiConfig.getHeadsMap());
        return resultJson;
    }

    public Integer queryBankerProduct(Integer bankerProductId) {
        List<BankerProductDetailResponse> bankerProductDetailResponseList = bankerProductDao.findInfoById(bankerProductId);
        if (CollectionUtils.isEmpty(bankerProductDetailResponseList)) {
            return null;
        }
        if (bankerProductDetailResponseList.size() == 1) {
            return bankerProductDetailResponseList.get(0).getBrandId();
        }
        bankerProductDetailResponseList.stream().sorted((stu1, stu2) ->
                        Long.compare(stu2.getProductCreatTime().getTime(), stu1.getProductCreatTime().getTime()))
                .forEach(System.out::println);

        return bankerProductDetailResponseList.get(0).getBrandId();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateGoods(GoodsRequest goodsRequest) {
        isUpdateDel(goodsRequest.getId());

        saveImg(goodsRequest);

        saveProductSpecAndSku(goodsRequest);

        goodsRequest.setAttributeJson(getSpecJson(goodsRequest.getSkuKey()));

        goodsRequest.setStock(goodsRequest.getSpec().stream().mapToInt(ProductSpecResponse::getStock).sum());

        Product oldProduct = productDao.getProductById(goodsRequest.getId());
        if (goodsRequest.getBankerColumnId() == 3) {
            goodsRequest.setIsZeroProduct(1);
            goodsRequest.setProductType(2);
            goodsRequest.setActivityType(ActivityEnums.ZERO_EVALUATION.getActivityCode());
        } else {
            goodsRequest.setIsZeroProduct(0);
            goodsRequest.setActivityType(oldProduct.getActivityType());
            goodsRequest.setProductType(oldProduct.getProductType());
            if (ActivityEnums.ZERO_EVALUATION.getActivityCode().equals(oldProduct.getActivityType())) {
                goodsRequest.setActivityType("");
                goodsRequest.setProductType(1);
            }
        }
        //计算总库存
        AtomicReference<Integer> stock = new AtomicReference<>(0);
        goodsRequest.getSpec().stream().forEach(s -> {
            stock.set(stock.get() + s.getStock());
        });
        //修改商品信息
        goodsDao.updateGoods(goodsRequest);
        //同步修改供应商商品信息
        syncBankerColumn(goodsRequest, stock.get());
        try {
            //同步商品sku到供应商商品库中
            doHandleBankerSystemInfo(goodsRequest, oldProduct.getBankerProductId());
        } catch (Exception e) {
            log.error("===更新供应商商品规格异常==={}", e);
        }
    }

    private void doHandleBankerSystemInfo(GoodsRequest goodsRequest, Integer bankerProdutId) {
        UpdateSkuRequest updateSkuRequest = new UpdateSkuRequest();
        updateSkuRequest.setBankerId(goodsRequest.getBankerId());
        updateSkuRequest.setProductId(bankerProdutId);
        updateSkuRequest.setSpec(goodsRequest.getSpec());
        updateSkuRequest.setSkuKey(goodsRequest.getSkuKey());
        bankerClient.updateProductSpec(updateSkuRequest);
    }

    private int updateBankerProductBrandId(Integer bankerProductId, Integer bankerBrandId) {
        log.debug("===updateBankerProductBrandId==={},{}", bankerProductId, bankerBrandId);
        if (null != bankerProductId) {//&& null != bankerBrandId
            int result = bankerProductDao.updateBrandIdById(bankerProductId, bankerBrandId);
            return result;
        }
        return 0;
    }

    @Override
    public List<EvaluationInfoResponse> getEvaluationInfo(GetEvaluationInfoRequest request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        return goodsDao.findEvaluationInfo(request);
    }

    @Override
    public List<EvaluationInfoDetailResponse> getEvaluationInfoDetail(Integer productId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return goodsDao.findEvaluationInfoDetail(productId);
    }

    @Override
    public List<EvaluationFeedbackResponse> getEvaluationFeedback(GetEvaluationFeedbackRequest request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        return goodsDao.findEvaluationFeedback(request);
    }

    /**
     * 保存商品规格 sku
     */
    public void saveProductSpecAndSku(GoodsRequest goodsRequest) {
        updateProductSpec(goodsRequest.getId(), goodsRequest.getSpec());
        List<ProductSkuKeyResponse> skuKey = goodsRequest.getSkuKey();
        for (ProductSkuKeyResponse productSkuKeyRequest : skuKey) {
            productSkuKeyRequest.setPid(goodsRequest.getId());
            goodsDao.saveSkuKey(productSkuKeyRequest);
            goodsDao.saveSkuValue(goodsRequest.getId(), productSkuKeyRequest.getId(), productSkuKeyRequest.getSkuValue());
        }
    }

    /**
     * 规格更新
     */
    public void updateProductSpec(Integer id, List<ProductSpecResponse> specList) {
        if (specList.size() > 0) {
            // 清空之前的规格spec 插入新规格
            List<Integer> ignoreIds = specList.stream().filter(s -> null != s.getId()).map(ProductSpecResponse::getId).collect(Collectors.toList());
            goodsDao.deleteSpecAndIgnoreIds(id, ignoreIds);
            for (ProductSpecResponse productSpecResponse : specList) {
                productSpecResponse.setProductId(id);
                if (null != productSpecResponse.getId()) {
                    goodsDao.updateSpecInfo(productSpecResponse);
                } else {
                    goodsDao.saveSpecInfo(productSpecResponse);
                }
            }
        }
    }

    /**
     * 获取规格JSON
     *
     * @param skuKey
     * @return
     */
    public String getSpecJson(List<ProductSkuKeyResponse> skuKey) {
        List<Map<String, Object>> specList = new ArrayList<>();
        for (ProductSkuKeyResponse productSkuKeyRequest : skuKey) {
            List<String> collect = productSkuKeyRequest.getSkuValue().stream().map(ProductSkuValueResponse::getValue).collect(Collectors.toList());
            Map<String, Object> map = new HashMap<>();
            map.put("spanName", productSkuKeyRequest.getName());
            map.put("spanValue", collect);
            specList.add(map);
        }
        return JSON.toJSONString(specList);
    }

    public void saveImg(GoodsRequest goodsRequest) {
        List<ProductImgResponse> bannerList = goodsRequest.getBannerList();
        for (ProductImgResponse productImgRequest : bannerList) {
            if (productImgRequest.getSort() == null) {
                throw new ApiException("商品轮播图-图片排序值不能为空！");
            }
            productImgRequest.setType("banner");
            productImgRequest.setProductId(goodsRequest.getId());
        }
        List<ProductImgResponse> infoList = goodsRequest.getInfoList();
        for (ProductImgResponse productImgRequest : infoList) {
            if (productImgRequest.getSort() == null) {
                throw new ApiException("商品主图-图片排序值不能为空！");
            }
            productImgRequest.setType("info");
            productImgRequest.setProductId(goodsRequest.getId());
        }
        bannerList.addAll(infoList);
        goodsDao.saveImg(bannerList);
    }

    /**
     * 更新商品时 删除sku  spec 信息
     */
    public void isUpdateDel(Integer productId) {
        goodsDao.deleteSkuKey(productId);
        goodsDao.deleteSkuValue(productId);
        goodsDao.deleteImg(productId, null);
    }

    /**
     * 修改商品时 需同步供应商商品
     *
     * @param goodsRequest
     * @param stock
     */
    public void syncBankerColumn(GoodsRequest goodsRequest, Integer stock) {
        Product product = productDao.getProductById(goodsRequest.getId());
        BankerBrand bankerBrand = productDao.getBrandByBankerId(goodsRequest.getBankerBrandId());

        bankerProductDao.synvBankerProductColumn(product.getBankerProductId(),
                goodsRequest.getBankerColumnId(),
                stock, goodsRequest.getCostPrice(),
                goodsRequest.getBankerBrandId(),
                null == bankerBrand ? "" : bankerBrand.getBrandName(),
                goodsRequest.getTopCategoryId(),
                goodsRequest.getCategoryId(),
                goodsRequest.getBottomCategoryId(),
                goodsRequest.getAddressId(),
                goodsRequest.getIsExit(),
                goodsRequest.getMailType(),
                goodsRequest.getMailNote());
    }

    /**
     * 修改商品时 需同步供应商商品-用于最新分类
     *
     * @param goodsRequest
     * @param stock
     */
    public void syncBankerColumnV2(GoodsRequest goodsRequest, Integer stock) {
        Product product = productDao.getProductById(goodsRequest.getId());
        BankerBrand bankerBrand = productDao.getBrandByBankerId(goodsRequest.getBankerBrandId());
        bankerProductDao.synvBankerProductColumnV2(product.getBankerProductId(),
                goodsRequest.getBankerColumnId(),
                stock, goodsRequest.getCostPrice(),
                goodsRequest.getBankerBrandId(),
                null == bankerBrand ? "" : bankerBrand.getBrandName(),
                goodsRequest.getAddressId());
        //修改供应商商品分类Id
        ProductAndCategoryExample productAndCategoryExample = new ProductAndCategoryExample();
        productAndCategoryExample.createCriteria().andProductIdEqualTo(product.getBankerProductId()).andIsCancelEqualTo(0);
        List<ProductAndCategory> productAndCategoryRequests = productAndCategoryMapper.selectByExample(productAndCategoryExample);
        if (productAndCategoryRequests.size() > 1) {
            throw new ApiException("修改商品分类失败：商品关系表中存在多个相同的商品Id");
        } else if (productAndCategoryRequests.size() == 1) {
            ProductAndCategory productAndCategory = productAndCategoryRequests.get(0);
            productAndCategory.setFirstId(goodsRequest.getTopCategoryId());
            productAndCategory.setSecondId(goodsRequest.getCategoryId());
            productAndCategory.setThirdId(goodsRequest.getBottomCategoryId());
            productAndCategoryMapper.updateByPrimaryKeySelective(productAndCategory);
        }
    }

    @Override
    public void updateBankerColumn(Integer productId, Integer bankerColumnId) {
        if (bankerColumnId == 3) {
            goodsDao.updateZeroProductStatus(productId, 1);
        } else {
            goodsDao.updateZeroProductStatus(productId, 0);
        }
        goodsDao.updateBankerColumn(productId, bankerColumnId);
    }

    @Override
    public List<EvaluationDetailedResponse> getEvaluationDetailed(GetEvaluationFeedbackRequest request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<EvaluationDetailedResponse> evaluationDetailed = goodsDao.getEvaluationDetailed(request);
        long l = System.currentTimeMillis();
        for (EvaluationDetailedResponse response : evaluationDetailed) {
            if (response.getStatus() == 1 && response.getInvalidTime().getTime() <= System.currentTimeMillis())
                response.setStatus(2);
            if (response.getStatus() > 2) response.setStatus(3);
            BigDecimal bigDecimal = BigDecimal.ZERO;
            if (response.getProductPrice().compareTo(BigDecimal.ZERO) != 0) {
                bigDecimal = response.getProductPriceKo().divide(response.getProductPrice(), 2, BigDecimal.ROUND_HALF_UP);
            }
            response.setRatio(bigDecimal);
        }
        return evaluationDetailed;
    }

    @Override
    public List<EvaluationDetailedInfoResponse> getEvaluationDetailedInfo(Integer id, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<EvaluationDetailedInfoResponse> responses = goodsDao.getEvaluationDetailedInfo(id);
        for (EvaluationDetailedInfoResponse response : responses) {
            BigDecimal bigDecimal = BigDecimal.ZERO;
            if (response.getProductPrice().compareTo(BigDecimal.ZERO) != 0) {
                bigDecimal = response.getUserCutPrice().divide(response.getProductPrice(), 2, BigDecimal.ROUND_HALF_UP);
            }
            response.setRatio(bigDecimal);
        }
        return responses;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateGoodsTwo(GoodsRequest goodsRequest) {
        List<ProductSpecResponse> spec = goodsDao.findSpecTwo(goodsRequest.getId());
        spec.stream().forEach(item -> {
            List<ProductSpecResponse> requestSpecList = goodsRequest.getSpec();
            List<ProductSpecResponse> matchList = requestSpecList.stream().filter(requestObj -> requestObj.getId().equals(item.getId())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(matchList)) {
                item.setProImg(matchList.get(0).getProImg());
            }
        });
        goodsRequest.setSpec(spec);

        isUpdateDel(goodsRequest.getId());

        saveImg(goodsRequest);

        saveProductSpecAndSku(goodsRequest);

        goodsRequest.setAttributeJson(getSpecJson(goodsRequest.getSkuKey()));

        goodsRequest.setStock(goodsRequest.getSpec().stream().mapToInt(ProductSpecResponse::getStock).sum());

        Product oldProduct = productDao.getProductById(goodsRequest.getId());
        if (oldProduct.getBankerColumnId() == 3) {
            goodsRequest.setIsZeroProduct(1);
            goodsRequest.setProductType(2);
            goodsRequest.setActivityType(ActivityEnums.ZERO_EVALUATION.getActivityCode());
        } else {
            goodsRequest.setIsZeroProduct(0);
            goodsRequest.setActivityType(oldProduct.getActivityType());
            goodsRequest.setProductType(oldProduct.getProductType());
            if (ActivityEnums.ZERO_EVALUATION.getActivityCode().equals(oldProduct.getActivityType())) {
                goodsRequest.setActivityType("");
                goodsRequest.setProductType(1);
            }
        }
        //计算总库存
        AtomicReference<Integer> stock = new AtomicReference<>(0);
        goodsRequest.getSpec().stream().forEach(s -> {
            stock.set(stock.get() + s.getStock());
        });
        //修改商品信息
        goodsDao.updateGoodsTwo(goodsRequest);
        //同步修改供应商商品信息(美工修改将原有商品信息中的成本价取出)
        goodsRequest.setCostPrice(oldProduct.getCostPrice());
        syncBankerColumn(goodsRequest, stock.get());

    }

    /**
     * 商品详情缓存key
     */
    public static final String PRODUCT_DETAILS_KEY = "PRODUCT_DETAILS_KEY";

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateGoods(ChannelGoodsRequest goodsRequest) {
        String platformData = goodsRequest.getPlatformData();
        String shopId = goodsRequest.getShopId();
        if (StringUtils.isEmpty(platformData) || StringUtils.isEmpty(shopId)) {
            throw new ApiException("渠道和平台选择项不能为空！");
        }
        String begin = supplyApiConfig.getShopId().substring(0, 5);
        String[] shopIds = shopId.split(",");
        if (platformData.contains("all")) {
            goodsRequest.setPlatformData("all");
        }
        if (shopId.contains("all")) {
            goodsRequest.setShopId("all");
        }
        try {
            //当前选择的渠道
            List<String> platformDataList = Arrays.stream(platformData.split(",")).collect(Collectors.toList());
            if("all".equals(platformData)){
                platformDataList = new ArrayList<>();
            }else if (!"all".equals(platformData) && platformData.contains(PlatformConstant.PROVINCE_PLATFORM)) {
                if (CollectionUtils.isEmpty(goodsRequest.getProvinceCodes())) {
                    //获取当前商品所有投放的地区
                    List<Product> products = productDao.queryAreaProductBySupplyIds(Lists.newArrayList(goodsRequest.getSupplyProductId()));
                    if (!CollectionUtils.isEmpty(products)) {
                        List<String> provincePlatform = products.stream().map(e -> e.getPlatformData()).collect(Collectors.toList());
                        platformDataList.addAll(provincePlatform);
                    }
                } else {
                    for (String provinceCode : goodsRequest.getProvinceCodes()) {
                        if(StringUtils.isEmpty(provinceCode)){
                            throw new ApiException("商品推广地区不能为空或空字符串！");
                        }
                        platformDataList.add(PlatformConstant.PROVINCE_PLATFORM + provinceCode);
                    }
                }
            }
            //1.处理当前平台
            if ("all".equals(platformData) || Arrays.stream(shopIds).anyMatch(e -> e.contains(begin))) {
                if (goodsRequest.getIsSync() != null && goodsRequest.getIsSync() == 1) {//不同步到指定渠道，仅修改当前商品
                    updateProductAllInfo(goodsRequest.getId(), goodsRequest);
                } else if (goodsRequest.getIsSync() != null && (goodsRequest.getIsSync() == 2 || goodsRequest.getIsSync() == 3)) {//同步，将修改的信息同步到指定渠道
                    List<Product> channelProducts = channelProductService.queryBySupplyIdAndPlatformData(Lists.newArrayList(goodsRequest.getSupplyProductId()), platformDataList);
                    if (!CollectionUtils.isEmpty(channelProducts)) {
                        List<Integer> productIdList = channelProducts.stream().map(Product::getId).collect(Collectors.toList());
                        for (Integer productId : productIdList) {
                            goodsRequest.setId(productId);
                            if(goodsRequest.getIsSync() == 2){
                                updateProductAllInfo(productId, goodsRequest);
                            }else if(goodsRequest.getIsSync() == 3){
                                updateProductPartInfo(productId, goodsRequest);
                            }
                        }
                    }
                }
            }
            //2.处理其他平台
            sendUpdateProductMessage(goodsRequest);
        } catch (Exception e) {
            log.error("修改商品信息错误");
            throw new ApiException(e.getMessage());
        }

    }

    public void sendUpdateProductMessage(ChannelGoodsRequest goodsRequest){
        String shopId = goodsRequest.getShopId();
        List<String> shopIdList = Lists.newArrayList(shopId.split(","));
        if (shopIdList.contains("all")) {
            SalesChannelsManagement management = new SalesChannelsManagement();
            management.setType(1);
            List<SalesChannelsManagement> allSalesChannels = salesChannelsManagementDao.getAllSalesChannels(management);
            shopIdList = allSalesChannels.stream().map(e -> e.getCode()).collect(Collectors.toList());
        }
        //移除当前平台标识
        shopIdList.remove(supplyApiConfig.getShopId());
        goodsRequest.setShopId(String.join(",", shopIdList));
        for (String id : shopIdList) {
            if (id.equals("GUOB004") || id.equals("GUOB005") || id.equals("GUOB006") || id.equals("GUOB007")) {
                guchuangRabbitTemplate.convertAndSend(QueueConstants.PRODUCT_UPDATE_QUEUE, JSON.toJSONString(goodsRequest));
            }
//            else if (id.equals("JUMD005") || id.equals("JUMD006") || id.equals("JUMD007")|| id.equals("JUMD008")) {
//                jumaiduoRabbitTemplate.convertAndSend(QueueConstants.PRODUCT_UPDATE_QUEUE, JSON.toJSONString(goodsRequest));
//            } else if (id.equals("YQKJ006") || id.equals("YQKJ007") || id.equals("YQKJ008") || id.equals("YQKJ009")) {
//                yiquanRabbitTemplate.convertAndSend(QueueConstants.PRODUCT_UPDATE_QUEUE, JSON.toJSONString(goodsRequest));
//            } else if (id.equals("ZXLP005") || id.equals("ZXLP006") || id.equals("ZXLP007") || id.equals("YQKJ008") ) {
//                zxlpRabbitTemplate.convertAndSend(QueueConstants.PRODUCT_UPDATE_QUEUE, JSON.toJSONString(goodsRequest));
//            } else if (id.equals("YGYX005") || id.equals("YGYX006") || id.equals("YGYX007") || id.equals("YGYX008") ) {
//                ygyxRabbitTemplate.convertAndSend(QueueConstants.PRODUCT_UPDATE_QUEUE, JSON.toJSONString(goodsRequest));
//            } else if (id.equals("YXHD005") || id.equals("YXHD006") || id.equals("YXHD007") || id.equals("YXHD008") ) {
//                yxhdRabbitTemplate.convertAndSend(QueueConstants.PRODUCT_UPDATE_QUEUE, JSON.toJSONString(goodsRequest));
//            } else if (id.equals("JCYX005") || id.equals("JCYX006") || id.equals("JCYX007") || id.equals("JCYX008") ) {
//                jckjRabbitTemplate.convertAndSend(QueueConstants.PRODUCT_UPDATE_QUEUE, JSON.toJSONString(goodsRequest));
//            }
        }

    }

//    public void updateGoodsDetail(Integer productId, ChannelGoodsRequest goodsRequest, Integer id) {
//        if (goodsRequest.getIsSync() != null && (goodsRequest.getIsSync() == 1 || goodsRequest.getIsSync() == 2 || productId.equals(id))) {
//            goodsDao.deleteImg(productId, null);
//            saveImg(goodsRequest);
//            updateProductSpecNew(productId, goodsRequest.getSpec(), goodsRequest.getIsSync());
//            //修改商品信息
//            goodsRequest.setVolume(org.springframework.util.StringUtils.isEmpty(goodsRequest.getVolumeStr()) ? 0 : parseInt(goodsRequest.getVolumeStr()));
//            goodsDao.updateGoodsNew(goodsRequest);
//        } else if (goodsRequest.getIsSync() != null && goodsRequest.getIsSync() == 3) {
//            goodsDao.deleteImg(productId, "info");
//            saveProductImg(goodsRequest);
//            goodsDao.updateProductLongTitle(goodsRequest.getId(), goodsRequest.getLongTitle(), goodsRequest.getProductName());
//        }
//
//
//        String key = RedisConstants.PRODUCT_DETAILS + PRODUCT_DETAILS_KEY + productId;
//        redisService.delete(key);
//    }

    /**
     * 仅更新商品长标题、商品名、详情图、轮播图、主图
     */
    public void updateProductPartInfo(Integer productId, ChannelGoodsRequest goodsRequest) {
        goodsDao.deleteImg(productId, "banner");
        goodsDao.deleteImg(productId, "info");
        saveProductImg(goodsRequest);
        List<ProductSpec> productSpecs = productSpecDao.selectByProductIds(Arrays.asList(productId));
        for (ProductSpec productSpec : productSpecs) {
            for (ProductSpecResponse reqSpec : goodsRequest.getSpec()) {
                if(productSpec.getSupplyId().equals(reqSpec.getSupplyId())){
                    goodsDao.updateSpecById(reqSpec.getProImg(),productSpec.getId());
                    break;
                }
            }
        }
        goodsDao.updateProductLongTitle(goodsRequest.getId(), goodsRequest.getLongTitle(), goodsRequest.getProductName(), goodsRequest.getProductImg());
        String key = RedisConstants.PRODUCT_DETAILS + PRODUCT_DETAILS_KEY + productId;
        redisService.delete(key);
    }

    /**
     * 更新商品信息填写的信息
     */
    public void updateProductAllInfo(Integer productId, ChannelGoodsRequest goodsRequest){
        goodsDao.deleteImg(productId, null);
        saveImg(goodsRequest);
        updateProductSpecNew(productId, goodsRequest.getSpec(), goodsRequest.getIsSync());
        //修改商品信息
        goodsRequest.setVolume(org.springframework.util.StringUtils.isEmpty(goodsRequest.getVolumeStr()) ? 0 : parseInt(goodsRequest.getVolumeStr()));
        goodsDao.updateGoodsNew(goodsRequest);
        String key = RedisConstants.PRODUCT_DETAILS + PRODUCT_DETAILS_KEY + productId;
        redisService.delete(key);
    }

    @Override
    public void updateGoodsStatusByPrc(String bankerProductIds) {
        List<String> bankerProductIdList = Arrays.asList(bankerProductIds.split(","));
        if (CollectionUtils.isEmpty(bankerProductIdList)) {
            return;
        }
        log.debug("===updateGoodsStatusByPrc==={}", JSONObject.toJSONString(bankerProductIdList));
        List<Integer> bankerProductIdList_Integer = bankerProductIdList.stream().map(Integer::parseInt).collect(Collectors.toList());
        ProductExample productExample = new ProductExample();
        productExample.createCriteria().andBankerProductIdIn(bankerProductIdList_Integer).andStatusEqualTo(new Byte("1"));
        List<Product> productList = productMapper.selectByExample(productExample);
        if (CollectionUtils.isEmpty(productList)) {
            return;
        }
        productList.stream().forEach(item -> {
            item.setStatus(ProductStatusEnums.DOW.getValue());
            productMapper.updateByPrimaryKeySelective(item);
        });
    }

    public void saveImg(ChannelGoodsRequest goodsRequest) {
        List<ProductImgResponse> addList = new ArrayList<>();
        List<ProductImgResponse> bannerList = goodsRequest.getBannerList();
        for (ProductImgResponse productImgRequest : bannerList) {
            if (productImgRequest.getSort() == null) {
                throw new ApiException("商品轮播图-图片排序值不能为空！");
            }
            productImgRequest.setType("banner");
            productImgRequest.setProductId(goodsRequest.getId());
        }
        List<ProductImgResponse> infoList = goodsRequest.getInfoList();
        if (!CollectionUtils.isEmpty(infoList)) {
            for (ProductImgResponse productImgRequest : infoList) {
                if (productImgRequest.getSort() == null) {
                    throw new ApiException("商品主图-图片排序值不能为空！");
                }
                productImgRequest.setType("info");
                productImgRequest.setProductId(goodsRequest.getId());
            }
        }
        addList.addAll(infoList);
        addList.addAll(bannerList);
        goodsDao.saveImg(addList);
    }

    public void saveProductImg(ChannelGoodsRequest goodsRequest) {
        List<ProductImgResponse> addList = new ArrayList<>();
        List<ProductImgResponse> bannerList = goodsRequest.getBannerList();
        for (ProductImgResponse productImgRequest : bannerList) {
            if (productImgRequest.getSort() == null) {
                throw new ApiException("商品轮播图-图片排序值不能为空！");
            }
            productImgRequest.setType("banner");
            productImgRequest.setProductId(goodsRequest.getId());
        }
        List<ProductImgResponse> infoList = goodsRequest.getInfoList();
        if (!CollectionUtils.isEmpty(infoList)) {
            for (ProductImgResponse productImgRequest : infoList) {
                if (productImgRequest.getSort() == null) {
                    throw new ApiException("商品主图-图片排序值不能为空！");
                }
                productImgRequest.setType("info");
                productImgRequest.setProductId(goodsRequest.getId());
            }
        }
        addList.addAll(infoList);
        addList.addAll(bannerList);
        goodsDao.saveImg(addList);
    }

    public void updateProductSpecNew(Integer id, List<ProductSpecResponse> specList, Integer isSync) {
        List<Integer> supplyIdList = specList.stream().map(ProductSpecResponse::getSupplyId).collect(Collectors.toList());
        List<ProductSpecResponse> productSpecsList = null;
        if (isSync != null && isSync == 2) {
            List<Integer> idList = specList.stream().map(ProductSpecResponse::getId).collect(Collectors.toList());
            productSpecsList = productSpecDao.selectBySupIdList(supplyIdList, idList);
        }

        if (specList.size() > 0) {
            for (ProductSpecResponse productSpecResponse : specList) {
                productSpecResponse.setProductId(id);
                productSpecResponse.setStatus(null == productSpecResponse.getStatus() ? 1 : productSpecResponse.getStatus());
                if (null != productSpecResponse.getId()) {
                    goodsDao.updateSpecInfoApp(productSpecResponse);
                }
                if (!CollectionUtils.isEmpty(productSpecsList)) {
                    List<ProductSpecResponse> otherSpecList = productSpecsList.stream().filter(item -> item.getSupplyId().equals(productSpecResponse.getSupplyId())
                            && id.equals(item.getProductId())).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(otherSpecList)) {
                        for (ProductSpecResponse otherSpec : otherSpecList) {
                            Integer otherSpecId = otherSpec.getId();
                            BeanUtils.copyProperties(productSpecResponse, otherSpec);
                            otherSpec.setId(otherSpecId);
                            goodsDao.updateSpecInfoApp(otherSpec);
                        }
                    }
                }
            }
        }


    }
}
